package com.lmh.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lmh.common.core.domain.TableDataInfo;
import com.lmh.friend.domain.question.Question;
import com.lmh.friend.domain.question.dto.QuestionQueryDTO;
import com.lmh.friend.domain.question.es.QuestionES;
import com.lmh.friend.domain.question.vo.QuestionDetailVO;
import com.lmh.friend.domain.question.vo.QuestionVO;
import com.lmh.friend.elasticsearch.QuestionRepository;
import com.lmh.friend.manager.QuestionCacheManager;
import com.lmh.friend.mapper.question.QuestionMapper;
import com.lmh.friend.service.question.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {
    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionCacheManager questionCacheManager;
    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        // 首先看es中是否存在数据
        long count = questionRepository.count();
        if (count <= 0) {
            refreshQuestion();
        }
        // 此时es中是存在数据的，然后我们根据前端传来的查询信息来决定调用哪个方法
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum()-1, questionQueryDTO.getPageSize(),sort);
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();
        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyword)) {
            // 如果没有查询条件的话，就实现分页查询
            questionESPage = questionRepository.findAll(pageable);
        }else if (difficulty == null) {
            questionESPage = questionRepository.findByTitleOrContent(keyword,keyword,pageable);
        }else if (StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty,pageable);
        }else {
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword,keyword,difficulty,pageable);
        }
        long total = questionESPage.getTotalElements();
        if (total <= 0) {
            return TableDataInfo.empty();
        }
        List<QuestionES> questionESList = questionESPage.getContent();
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList,total);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        // 先从es中查找该题目是否存在
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES != null) {
            BeanUtil.copyProperties(questionES,questionDetailVO);
            return questionDetailVO;
        }
        // 如果es中不存在，那就从数据库中查，然后刷新es
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            return null;
        }
        // 刷新es
        refreshQuestion();
        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    /**
     * 如果得到当前题目的前一道题目呢，因为我们在返回题目列表的时候是按照题目的创建时间降序排列的，所以我们可以从数据库中查一遍题目列表，然后找到当前题目，
     * 自然而然就找到当前吗题目的前一道题目了，但是这里可以对其进行优化，因为每个用户获取到的题目列表的数据都是一样的，所以我们可以将题目的列表顺序存储
     * 在redis中，并且是以list类型进行存储，list中只需要存储题目的questionId
     * @param questionId
     * @return
     */
    @Override
    public String preQuestion(Long questionId) {
        // 首先看redis中是否存在题目列表顺序的数据
        Long listSize = questionCacheManager.getListSize();
        // 如果不存在就刷新缓存
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        // 然后根据当前题目id找到前一个题目
        return questionCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        // 首先看redis中是否存在题目列表顺序的数据
        Long listSize = questionCacheManager.getListSize();
        // 如果不存在就刷新缓存
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        // 然后根据当前题目id找到前一个题目
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    @Override
    public List<QuestionVO> getHotQuestionList() {
        // 先从redis中获取热榜信息
        List<Long> questionIdList = questionCacheManager.getHotQutsionList();
        // 不存在热榜信息则从MySQL中获取
        if (CollectionUtil.isEmpty(questionIdList)) {
            questionIdList = questionCacheManager.refreshHotQuestionList();
        }
        List<QuestionVO> questionVOList = new ArrayList<>();
        // redis中只存储题目的id，然后我们再根据questionId获取题目的title
        for (Long id : questionIdList) {
            QuestionVO questionVO = new QuestionVO();
            // 先从es中获取
            QuestionES questionES = questionRepository.findById(id).orElse(null);
            // 不存在则从MySQL中获取，并且将其刷新到es中
            if (questionES == null) {
                questionES = new QuestionES();
                Question question = questionMapper.selectById(id);
                BeanUtil.copyProperties(question,questionES);
                questionRepository.save(questionES);
            }
            questionVO.setQuestionId(questionES.getQuestionId());
            questionVO.setTitle(questionES.getTitle());
            questionVOList.add(questionVO);
        }
        return questionVOList;
    }

    private void refreshQuestion() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }
}
